package cn.com.jslh.boarpro.main.presenter;

import android.content.Context;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimAdapterEx;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.com.jslh.boarpro.R;
import cn.com.jslh.boarpro.main.contract.AddTemplateContract;
import cn.com.jslh.boarpro.main.model.AddTemplateModelImpl;
import cn.com.jslh.boarpro.main.view.fragment.RecordTemplateFragment;
import cn.com.jslh.boarpro.main.view.fragment.ShowPigInfoFragment;
import cn.com.jslh.boarpro.util.WebService;
import cn.com.jslh.boarpro.util.database.DataBaseUtil;
import cn.com.jslh.boarpro.util.template.AdapterInterface;
import cn.com.jslh.boarpro.util.template.AddTempBaseItem;
import cn.com.jslh.boarpro.util.template.BaseAction;
import cn.com.jslh.boarpro.util.template.TemplateFactory;
import cn.com.jslh.boarpro.util.template.TemplateHelper;

/**
 * Created by Administrator on 2017/11/17.
 */

public class AddTemplatePresenterImpl implements AddTemplateContract.Presenter {

    private Context context;
    private AddTemplateContract.View view;
    private AddTemplateContract.Model model;
    private SlimAdapterEx adapter;
    private JSONArray config;

    public AddTemplatePresenterImpl(Context context, AddTemplateContract.View view) {
        view.setPresenter(this);
        this.view = view;
        this.context = context;
        this.model = new AddTemplateModelImpl();
    }

    @Override
    public void start() {
        model.getDatas(context, new WebService.NetSuccessListener() {
            @Override
            public void Success(String s) throws JSONException {
                JSONObject jsonObjectAll = new JSONObject(s);
                config = jsonObjectAll.getJSONArray("config");//解析Config
                //解析事件,将事件存入数据库
                //便于事件查找，组件与事件交互处理
                JSONArray actions = jsonObjectAll.getJSONArray("actions");
//                DataBaseUtil.clearTable(context, BaseAction.class);
                DataBaseUtil.saveJsonArrayData(context, BaseAction.class, actions);
                //解析items，将items存入数据库(?是否有必要),组件调整数据都调整数据库数据，界面更新时，只与数据库交互，
                //实现组件Template分离，同时处理 iskeep等界面离开后数据保留等信息
//                DataBaseUtil.clearTable(context, AddTempBaseItem.class);
                JSONArray body = jsonObjectAll.getJSONArray("body");
                DataBaseUtil.saveJsonArrayData(context, AddTempBaseItem.class, body);
                adapter.updateData(getDatasFromDatabase()).notifyDataSetChanged();
            }
        });
    }

    /**
     * 从数据库获取ItemsDatas
     *
     * @return
     */
    public List<AddTempBaseItem> getDatasFromDatabase() {
        List<AddTempBaseItem> datas = new ArrayList<>();
        ArrayList<Object> jsonObject = DataBaseUtil.GetData(context, AddTempBaseItem.class);
        for (int i = 0; i < jsonObject.size(); i++) {
            AddTempBaseItem o = TemplateFactory.createTempItem(((AddTempBaseItem) jsonObject.get(i)).getItemtype());
            o.injectData((AddTempBaseItem) jsonObject.get(i));
            datas.add(o);
        }
        return datas;
    }

    @Override
    public void bindRV(RecyclerView recyclerView) {
        adapter= null;
        adapter = SlimAdapter.create(SlimAdapterEx.class)
                .enableDiff()
                .enableEmptyView(recyclerView.getContext(), R.layout.empty_layout)
                .registerDefault(R.layout.add_template_def_item_layout, new SlimInjector() {
                    @Override
                    public void onInject(Object data, IViewInjector injector) {
                    }
                });

        for (int i = 0; i < TemplateFactory.classArrayList.size(); i++) {
            Class cls = TemplateFactory.classArrayList.get(i);
            try {
                Object o = cls.newInstance();
                if (o instanceof AdapterInterface) {
                    AdapterInterface adapterInterface = (AdapterInterface) o;
                    adapter.register(adapterInterface.getLayout(), adapterInterface.getSlimInjetor());
                }
            } catch (InstantiationException e) {
//                e.printStackTrace();
            } catch (IllegalAccessException e) {
//                e.printStackTrace();
            }
        }
        adapter.attachTo(recyclerView);
    }


    @Override
    public void initShowPigInfoFragment(FragmentManager fm) {
        ShowPigInfoFragment.initInfoShowFragment(fm);
    }

    @Override
    public void refresh() {
        adapter.updateData(getDatasFromDatabase()).notifyDataSetChanged();
    }

    @Override
    public void subAction() {
        try {
            if (TemplateHelper.required(context)) //必填字段检查
                return;
            if((((JSONObject) config.getJSONObject(0)).getInt("isCheck"))==1){
                TemplateHelper.doAction(context, ((JSONObject) config.getJSONObject(0)).getString("checkAction"), new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        JSONObject jsonObject1 = new JSONObject(s);
                        if (jsonObject1.getString("flag").equals("1")) {
                            TemplateHelper.doAction(context, ((JSONObject) config.getJSONObject(0)).getString("buttonAction"), new WebService.NetSuccessListener() {
                                @Override
                                public void Success(String s) throws JSONException {
                                    JSONObject jsonObject1 = new JSONObject(s);
                                    if (jsonObject1.getString("flag").equals("1")) {
                                        //通过
                                        Toast.makeText(context, jsonObject1.getString("data"), Toast.LENGTH_SHORT).show();
                                        //refresh
                                        //更新
                                        TemplateHelper.doRefresh(context);
                                        ShowPigInfoFragment.postEvent(new JSONArray());
                                        RecordTemplateFragment.reFresh();
                                    } else {
                                        Toast.makeText(context, jsonObject1.getString("data"), Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        } else {
                            Toast.makeText(context, jsonObject1.getString("data"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }else {
                TemplateHelper.doAction(context, ((JSONObject) config.getJSONObject(0)).getString("buttonAction"), new WebService.NetSuccessListener() {
                    @Override
                    public void Success(String s) throws JSONException {
                        JSONObject jsonObject1 = new JSONObject(s);
                        if (jsonObject1.getString("flag").equals("1")) {
                            //通过
                            Toast.makeText(context, jsonObject1.getString("data"), Toast.LENGTH_SHORT).show();
                            //refresh
                            //更新
                            TemplateHelper.doRefresh(context);
                            //
                            ShowPigInfoFragment.postEvent(new JSONArray());

                            RecordTemplateFragment.reFresh();
                        } else {
                            Toast.makeText(context, jsonObject1.getString("data"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
